<?php

class IndexController extends Zend_Controller_Action
{
    function init()
    {
        $this->db = Zend_Registry::get("db");
    }
    
    function preDispatch()
    {
		if(!$_SESSION['init'])
		{
			$mod = new Sys_Init();
			$mod->LoadBaseInfoToSession();
		}
		
		$this->view->layout = "front";
		
		$params = $this->_request->getParams();	
    }
	
	function indexAction()
	{
		$params = $this->_request->getParams();
		
		if($params['channel_id'])
		{
			$channel_id = $params['channel_id'];
		}else{
			$channel_id = 0;
		}
		
		$ext = new Sys_Extensions();
		
		if($ext->IsFromWechat())
		{
			if($params['state'])
			{
				$state = $params['state'];
			}elseif($params['redirect_uri'])
			{
				$_SESSION['redirect_uri'] = $params['redirect_uri'];
				$state = 555; //跳转专用代码
			}else{
				$state = 0;
			}
			
			$mod_params = new Db_Tables_SysParams();
			$base_url = $mod_params->GetVal('base_url');
			$app_id = $mod_params->GetVal('AppIdWX');
			
			$url = $base_url.'index/auth-index/channel_id/'.$channel_id;
			$url_encode = urlencode($url);
			
			$this->_redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$app_id."&redirect_uri=".$url_encode."&response_type=code&scope=snsapi_userinfo&state=".$state."#wechat_redirect");
		}else{
			if(!$_SESSION['member_info'])
			{
				$_SESSION['member_info'] = array();
			}

			$_SESSION['member_info']['not_from_wechat'] = TRUE;
			
			if($params['redirect_uri'])
			{
				$this->_redirect($params['redirect_uri']);
			}elseif($channel_id)
			{
				$this->_redirect('/index/dashboard/channel_id/'.$channel_id);
			}else{
				$this->_redirect('/index/channels');
			}
		}
	}
    
	function authIndexAction()
	{
		$params = $this->_request->getParams();
		
		if($params['testmode'])
		{
			$open_id = 'WECHATINITTEST1';
		}else{
			$mod_params = new Db_Tables_SysParams();
			$app_id = $mod_params->GetVal('AppIdWX');
			$app_secret = $mod_params->GetVal('AppSecretWX');

			$ch = curl_init();

			$str ='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$app_id.'&secret='.$app_secret.'&code='.$params['code'].'&grant_type=authorization_code';
			curl_setopt($ch, CURLOPT_URL, $str);
			curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
			$output = curl_exec($ch);

			$wechat_result = Zend_Json::decode($output);
			
			if($wechat_result['unionid'])
			{
				$open_id = $wechat_result['unionid'];
			}else{
				$open_id = $wechat_result['openid'];
			}
			
			//save & update info
			$str2 ='https://api.weixin.qq.com/sns/userinfo?access_token='.$wechat_result['access_token'].'&openid='.$open_id.'&lang=zh_CN';
			curl_setopt($ch, CURLOPT_URL, $str2);
			curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
			$output2 = curl_exec($ch);
			
			$wechat_result2 = Zend_Json::decode($output2);
			
			$mod_members_wechat = new Db_Tables_MembersWechat();
			$mod_members_wechat->open_id = $open_id;
			$mod_members_wechat->gender = $wechat_result2['sex'];
			$mod_members_wechat->nick_name = $wechat_result2['nickname'];
			$mod_members_wechat->head_image = $wechat_result2['headimgurl'];
			$mod_members_wechat->UpdateWechatInfo();
		}
		
		//add openid into session
		if(!$_SESSION['member_info'])
		{
			$_SESSION['member_info'] = array();
		}
		
		$_SESSION['member_info']['open_id'] = $open_id;
		
		//check member info
		$mod_members_wechat = new Db_Tables_MembersWechat();
		$wechat_row = $mod_members_wechat->fetchRow("open_id='".$open_id."'");
		
		//auto login
		if($wechat_row)
		{
			$mod_members = new Db_Tables_Members();
			$mod_members->member_id = $wechat_row->member_id;
			$mod_members->LoadMemberInfoToSession();
		}
		
		if(555 == $params['state']) //跳回原处
		{
			if($_SESSION['redirect_uri'])
			{
				$this->_redirect($_SESSION['redirect_uri']);
			}else{
				if($params['channel_id'])
				{
					$this->_redirect('/index/dashboard/channel_id/'.$params['channel_id']);
				}else{
					$this->_redirect('/index/channels');
				}
			}
		}else{
			if($params['channel_id'])
			{
				$this->_redirect('/index/dashboard/channel_id/'.$params['channel_id']);
			}else{
				$this->_redirect('/index/channels');
			}
		}
	}
	
	function channelsAction()
	{
		if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"])
		{
		$ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
		}
		elseif ($HTTP_SERVER_VARS["HTTP_CLIENT_IP"])
		{
		$ip = $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
		}
		elseif ($HTTP_SERVER_VARS["REMOTE_ADDR"])
		{
		$ip = $HTTP_SERVER_VARS["REMOTE_ADDR"];
		}
		elseif (getenv("HTTP_X_FORWARDED_FOR"))
		{
		$ip = getenv("HTTP_X_FORWARDED_FOR");
		}
		elseif (getenv("HTTP_CLIENT_IP"))
		{
		$ip = getenv("HTTP_CLIENT_IP");
		}
		elseif (getenv("REMOTE_ADDR"))
		{
		$ip = getenv("REMOTE_ADDR");
		}
		else
		{
		$ip = "Unknown";
		} 
		
		$url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=".$ip;
		$location_json = file_get_contents($url);
		$location_info = Zend_Json::decode($location_json);
		
		$params = $this->_request->getParams();	
		$this->view->title = "领彩乐道";
		
		$mod_channels = new Db_Tables_Channels();
		$this->view->provinces = $mod_channels->GetProvinces();
		
		if($params['province'])
		{
			$mod_channels->province = $params['province'];
			$this->view->province = $params['province'];
		}elseif($location_info['province'])
		{
			if(in_array($location_info['province'], $this->view->provinces))
			{
				$mod_channels->province = $location_info['province'];
				$this->view->province = $location_info['province'];
			}
		}
		
		$this->view->channels = $mod_channels->GetChannels();
		
		$mod_banners = new Db_Tables_TopBanners();
		$mod_banners->channel_id = 0;
		$this->view->top_banners = $mod_banners->LoadBanners();
		
		$this->view->channel_title = 1;
	}

	function dashboardAction()
	{
		if(!$_SESSION['member_info']['not_from_wechat'] && !$_SESSION['member_info']['open_id'])
		{
			$this->_redirect("/?redirect_uri=".$_SERVER['REQUEST_URI']);
		}
		
		$params = $this->_request->getParams();	
		$this->view->title = "领彩乐道";
		
		if($params['channel_id'])
		{
			$channel_id = $params['channel_id'];
		}elseif($_SESSION['site_info']['channel_id'])
		{
			$channel_id = $_SESSION['site_info']['channel_id'];
		}else{
			$channel_id = 1;
		}
		
		$mod_banners = new Db_Tables_TopBanners();
		$mod_banners->channel_id = $channel_id;
		$this->view->top_banners = $mod_banners->LoadBanners();
		
		$mod_level_joins = new Db_Joins_LevelJoins();
		$mod_level_joins->channel_id = $channel_id;
		
		if($params['category'])
		{
			$mod_level_joins->cateogry = $params['category'];
		}
		
		if($params['keyword'])
		{
			$mod_level_joins->keyword = $params['keyword'];
		}
		
		$this->view->items = $mod_level_joins->GetHomePageProducts();
	}
	
	function level1Action()
	{
		if(!$_SESSION['member_info']['not_from_wechat'] && !$_SESSION['member_info']['open_id'])
		{
			$this->_redirect("/?redirect_uri=".$_SERVER['REQUEST_URI']);
		}
		
		$params = $this->_request->getParams();	
		
		if($params['level_id'])
		{
			$this->view->level_id = $params['level_id'];
			
			$mod_top_banners = new Db_Tables_TopBanners();
			$mod_top_banners->level = 1;
			$mod_top_banners->level_id = $params['level_id'];
			$this->view->banners = $mod_top_banners->LoadBanners();
			
			$mod_level_joins = new Db_Joins_LevelJoins();

			if($params['category'])
			{
				$mod_level_joins->cateogry = $params['category'];
			}

			if($params['keyword'])
			{
				$mod_level_joins->keyword = $params['keyword'];
			}
			
			$mod_level_joins->level_id = $params['level_id'];

			$this->view->items = $mod_level_joins->GetLevel1PageProducts();
			
			$mod_level1 = new Db_Tables_Level1();
			$mod_level1->level1_id = $params['level_id'];
			$mod_level1->LoadChannelIdToSession($mod_level1->GetChannelId());
		}else{
			$this->_redirect("/");
		}
	}
	
	function level2Action()
	{
		if(!$_SESSION['member_info']['not_from_wechat'] && !$_SESSION['member_info']['open_id'])
		{
			$this->_redirect("/?redirect_uri=".$_SERVER['REQUEST_URI']);
		}
		
		$params = $this->_request->getParams();	
		
		if($params['level_id'])
		{
			$this->view->level_id = $params['level_id'];
			
			$mod_top_banners = new Db_Tables_TopBanners();
			$mod_top_banners->level = 2;
			$mod_top_banners->level_id = $params['level_id'];
			$this->view->banners = $mod_top_banners->LoadBanners();
			
			$mod_level_joins = new Db_Joins_LevelJoins();

			$mod_level_joins->level_id = $params['level_id'];

			$this->view->items = $item = $mod_level_joins->GetLevel2PageProducts();
			
			$mod_level2 = new Db_Tables_Level2();
			$mod_level2->level_id = $params['level_id'];
			$this->view->contents = $mod_level2->LoadContents();
			
			$mod_level1 = new Db_Tables_Level1();
			$mod_level1->level1_id = $item[0]['level1_id'];
			$mod_level1->LoadChannelIdToSession($mod_level1->GetChannelId());
		}else{
			$this->_redirect("/");
		}
	}
	
	function level3Action()
	{
		if(!$_SESSION['member_info']['not_from_wechat'] && !$_SESSION['member_info']['open_id'])
		{
			$this->_redirect("/?redirect_uri=".$_SERVER['REQUEST_URI']);
		}
		
		$params = $this->_request->getParams();	
		
		if($params['level_id'])
		{
			$mod_top_banners = new Db_Tables_TopBanners();
			$mod_top_banners->level = 3;
			$mod_top_banners->level_id = $params['level_id'];
			$this->view->banners = $mod_top_banners->LoadBanners();
			
			$mod_level_joins = new Db_Joins_LevelJoins();

			$mod_level_joins->level_id = $params['level_id'];

			$this->view->item = $item = $mod_level_joins->GetLevel3Details();
			$this->view->status = $mod_level_joins->GetLevel3Status();
			
			$mod_level1 = new Db_Tables_Level1();
			$mod_level1->level1_id = $item['level1_id'];
			$mod_level1->LoadChannelIdToSession($mod_level1->GetChannelId());
			
			// +1
			$mod_joined_item = new Db_Tables_MembersJoinedItems();
			$mod_joined_item->level3_id = $params['level_id'];
			$mod_joined_item->AddJoinedMembers();
		}else{
			$this->_redirect("/");
		}
	}
	
	function joinItemAction()
	{
		if(!$_SESSION['member_info']['not_from_wechat'] && !$_SESSION['member_info']['open_id'])
		{
			$this->_redirect("/?redirect_uri=".$_SERVER['REQUEST_URI']);
		}
		
		$this->_helper->layout->disableLayout();
		$params = $this->_request->getParams();	
		
		if($params['level_id'])
		{
			if($_SESSION['member_info']['member_id'])
			{
				$mod_members_joined_items = new Db_Tables_MembersJoinedItems();
				$mod_members_joined_items->member_id = $_SESSION['member_info']['member_id'];
				$mod_members_joined_items->level3_id = $params['level_id'];
				$mod_members_joined_items->AddRecord();

				$mod_level3 = new Db_Tables_Level3();
				$row = $mod_level3->fetchRow("id=".$params['level_id']);

				if($row)
				{
					if($_SESSION['member_info']['cellphone'])
					{
						$url = "http://wap.lingcaibao.com/mobile/channel/loginJump";
						$data_array = array(
							'username' => $_SESSION['member_info']['cellphone']
						);

						$mod = new Sys_LcbApi();
						$lcb_url = $mod->CallServerGet($url, $data_array);
						
//						$this->view->url = $lcb_url."&errorUrl=".urlencode("http://m.hypercomm.cn/index/dashboard")."&redirectUrl=".urlencode($row->external_url);
						$this->_redirect($lcb_url."&errorUrl=".urlencode("http://m.hypercomm.cn/index/dashboard")."&redirectUrl=".urlencode($row->external_url));
					}
				}else{
					$this->_redirect("/members/login/level3_id/".$params['level_id']);
				}
			}else{
				$this->_redirect("/members/login/level3_id/".$params['level_id']);
			}
			
		}else{
			$this->_redirect("/");
		}
	}
}